package com.meng.imrongyun.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.meng.baselibrary.fragment.BaseFragment;
import com.meng.imrongyun.R;
import com.meng.imrongyun.adapter.RecentConversationAdapter;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.message.TextMessage;

/**
 * Created by Administrator on 2017/5/15.
 */

public class RecentConversationListFragment extends BaseFragment {
    RecyclerView recyclerView;
    private RecentConversationAdapter conversationAdapter;

    @Override
    protected int getContentViewLayout() {
        return R.layout.fragment_subconversation_list;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initConversationList();
    }

    @Override
    protected void initView() {
        initPaddingTob();
        recyclerView = findViewById(R.id.recycleView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

    }

    @Override
    protected void initData() {


    }
    private List<Conversation> mData = new ArrayList<>();
    private void initConversationList() {
        RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                if (conversations != null) {
                    mData.clear();
                    mData.addAll(conversations);
                    if(conversationAdapter == null){
                        conversationAdapter = new RecentConversationAdapter(context,mData,R.layout.item_recent_message);
                        recyclerView.setAdapter(conversationAdapter);
                    }else{
                        conversationAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMessageEvent(TextMessage textMessage) {
        initConversationList();
    };
}
